package com.game.common.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: zhaoyongke
 * @create: 2024-05-30 08:54
 * @description: 微信
 */
public class WxUtils {

    private   static   String       xcx_appId="wxf60b4bc52899919f";

    private   static   String       xcx_secretKey="c75661d0708f2e39f0aaf077d97771a3";

    // 微信App的配置
    private   static   String       app_appId="wx2f1489d4c4975be6";

    private   static   String       app_secretKey="3b9df53c617de12aa2aea85e14b54fa9";


    // 微信小程序 拿code 换取openid
    public static Map<String,String> getWxOpenId(String code) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        // 请求微信服务器，获取用户 oppenid

        // 微信url
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + xcx_appId
                + "&secret=" + xcx_secretKey + "&js_code=" + code + "&grant_type=authorization_code";
        //客户端
        OkHttpClient client = new OkHttpClient();
        //用url发起请求
        Request request = new Request.Builder().url(url).build();
        //拿到响应
        Response response = client.newCall(request).execute();
        //如果响应成功，打印返回值
        if (response.isSuccessful()) {
            String body = response.body().string();
            JSONObject jsonObjectResult = JSON.parseObject(body);
            Object openid = jsonObjectResult.get("openid");
            Object unionid = jsonObjectResult.get("unionid");
            System.out.println("openId:::"+openid+"unionId:"+unionid);
            System.out.println("微信code：：：：" + code + "微信openid：" + body + "微信url：" + url);
            map.put("openId",openid.toString());
            map.put("unionId",unionid.toString());
            return map ;
        }
        return  map;
    }

    // 微信App 拿code 换取openid 和 unionid
    public static Map<String,String> getWxAppOpenId(String code) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        // 请求微信服务器，获取用户 openid 和 unionid

        // 微信App授权获取 openid 的url
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + app_appId
                + "&secret=" + app_secretKey + "&code=" + code + "&grant_type=authorization_code";

        //客户端
        OkHttpClient client = new OkHttpClient();
        //用url发起请求
        Request request = new Request.Builder().url(url).build();
        //拿到响应
        Response response = client.newCall(request).execute();
        //如果响应成功，打印返回值
        if (response.isSuccessful()) {
            String body = response.body().string();
            JSONObject jsonObjectResult = JSON.parseObject(body);

            // 检查是否有错误
            if (jsonObjectResult.containsKey("errcode")) {
                System.out.println("微信App获取openid失败，错误码：" + jsonObjectResult.get("errcode"));
                return map;
            }

            Object openid = jsonObjectResult.get("openid");
            Object unionid = jsonObjectResult.get("unionid");
            System.out.println("App openId:::"+openid+" unionId:"+unionid);
            System.out.println("微信App code：：：：" + code + " 微信App返回数据：" + body + " 请求url：" + url);

            if (openid != null) {
                map.put("openId",openid.toString());
            }

            if (unionid != null) {
                map.put("unionId",unionid.toString());
            }

            return map;
        }
        return  map;
    }


//    public static String getAccessToken() throws Exception {
////        Object cacheObject_token = redisService.getCacheObject("WX_TOKEN");
////        if(cacheObject_token!=null){
////            log.info("开始获取token=======================从缓存中获取token======================:"+cacheObject_token);
////            return String.valueOf(cacheObject_token);
////        }
//        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
//
//        String replaceUrl = url.replace("{0}", xcx_appId_dz).replace("{1}", xcx_secretKey_dz);
//        String res = HttpUtil.get(replaceUrl);
//        JSONObject object = JSONObject.parseObject(res);
//        Object access_token = object.get("access_token");
//        String expires_in = object.get("expires_in").toString();
////        redisService.setCacheObject("WX_TOKEN", access_token, Long.valueOf(expires_in), TimeUnit.SECONDS);
//        return access_token.toString();
//    }

    public static String  getMiniProgramCode( String  accessToken,String userId,String ercodeImage) throws Exception {
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));

        // 构建请求JSON数据
        JSONObject requestData = new JSONObject();
        requestData.put("scene", "userId="+userId);
        requestData.put("page", "pages/index/business_card/business_card");
        requestData.put("check_path", false);
        requestData.put("env_version", "trial");
//        requestData.put("env_version", "release");
        writer.write(requestData.toString());
        writer.flush();
        writer.close();
        InputStream inputStream = connection.getInputStream();

        BufferedImage bufferedImage = ImageIO.read(inputStream);
        ImageIO.write(bufferedImage, "jpg", new File(ercodeImage));
        String encode = Base64.encode(inputStream);
        inputStream.close();
        return encode;
    }


    public static String  getPhoneNumber(String code) throws Exception {
        //先根据appId和appSecret获取accessToken
        String tokenUrl = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", xcx_appId, xcx_secretKey);
        String accessToken = String.valueOf(JSON.parseObject(HttpUtil.get(tokenUrl)).get("access_token"));
        //通过token和code来获取用户手机号
        String url = String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?code=%s&access_token=%s", code, accessToken);
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", code);

        HttpHeaders headers = new HttpHeaders();
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap, headers);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Object> response = restTemplate.postForEntity(url, httpEntity, Object.class);

        String body = String.valueOf(response.getBody());// 解析JSON字符串s
        // 定义一个正则表达式来匹配 phoneNumber

        Pattern pattern = Pattern.compile("phoneNumber=(\\d+)");
        Matcher matcher = pattern.matcher(body);
        if (matcher.find()) {
            String phoneNumber = matcher.group(1); // 获取括号中的数字
            return phoneNumber;
        } else {
            return "";
        }
    }



}
